﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
/// <summary>
///WebMake 的摘要说明
/// </summary>
public class WebMake
{
	public WebMake()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}
    /// <summary>
    /// 获得推荐书籍列表
    /// </summary>
    /// <param name="iStrLen">字符串最大长度</param>
    /// <returns>书籍列表</returns>
    public static string getHotBook(int iStrLen)
    {
        //放回的字符串
        string sReturnString="";

        //查询出所有类型。
        SqlDataSource ds = new SqlDataSource();
        SqlDataSource ds2 = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds2.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        //检索类型
        ds.SelectCommand = "select BookType_ID,BookType_Name from ls_BookType order by BookType_ID";        
        ds2.SelectCommand = "select top 20 Book_Name,Book_ID from ls_Book where Book_Type=@booktype order by Book_WeekVisit desc";
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        DataView dv2; 
        for (int i = 0; i < dv.Count; i++)
        {
           // <div><div class="bt">修真</div><div class="bn"><a title="121">111</a></div></div> 
            sReturnString += "<div><div class=\"bt\">"+dv[i]["BookType_Name"]+"</div><div class=\"bn\">";
            //检索书籍
            int iLenTemp = 0;
            ds2.SelectParameters.Clear();
            ds2.SelectParameters.Add("booktype", dv[i]["BookType_ID"].ToString());
            dv2 = (DataView)ds2.Select(DataSourceSelectArguments.Empty);
            for (int j = 0; j < dv2.Count; j++)
            {
                string bookname=dv2[j]["Book_Name"].ToString();
                string bookid=dv2[j]["Book_ID"].ToString();
                iLenTemp += bookname.Length + 1;
                if (iLenTemp > iStrLen)
                    break;
                else
                {
                    sReturnString += " <a href=\"" + getBookPathByID(bookid) + "\">" + bookname + "</a> ";
                }
                
            }
            sReturnString += "</div></div>";
        }
        //各个类型输出
        return sReturnString;
    }
    /// <summary>
    /// 给清风小说浏览器的小说排名列表
    /// </summary>
    /// <param name="sType">类型，热点或者推荐。</param>
    /// <returns></returns>
    public static string getBooks(string sType)
    {
        string sSQLString = "";
        string sReturnStr = "";
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        switch (sType)
        {
            case "hot":
                sSQLString = "select BookType_Name,Book_Name,Book_ID from ls_Book inner join ls_BookType on BookType_ID=Book_Type where Book_ID in (select Top 100 Book_ID from ls_Book where Book_Good=0 order by Book_WeekVisit desc ) order by BookType_ID,Book_ID";
                break;
            default:
                sSQLString = "select BookType_Name,Book_Name,Book_ID from ls_Book inner join ls_BookType on BookType_ID=Book_Type where  Book_Good=1 order by BookType_ID,Book_ID";
                break;
        }
        ds.SelectCommand = sSQLString;
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        for (int i = 0; i < dv.Count; i++)
        {
            sReturnStr += "," + dv[i]["BookType_Name"].ToString() + "_" + dv[i]["Book_Name"].ToString() + "_" + dv[i]["Book_ID"].ToString();
        }
        sReturnStr = sReturnStr.Substring(1, sReturnStr.Length - 1);
        return sReturnStr;

    }
    /// <summary>
    /// 获得用户的书籍列表
    /// </summary>
    /// <param name="sUserName">用户名称</param>
    /// <returns></returns>
    public static string getBookList(string sUserName)
    {
        //返回格式
        //bookList(80634,'长生界','辰东','第392章 远古遗迹','2009-10-18',577337);
        string sReturn = "<script language=\"javascript\" type=\"text/javascript\">\r\n";
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.SelectCommand = "select Book_ID,Book_Name,Book_Writer,Book_LastChapter,DATENAME(yy,Book_LastTime)+'-'+DATENAME(mm,Book_LastTime)+'-'+DATENAME(dd,Book_LastTime) as Book_LastTime,";
        ds.SelectCommand += "Book_TotalVisit from ls_MyBook inner join ls_Book on Book_ID=MyBook_BookID where MyBook_UserName=@username";
        ds.SelectParameters.Add("username", sUserName);
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        if (dv != null && dv.Count > 0)
        {
            for (int i = 0; i < dv.Count; i++)
            {
                sReturn += "bookList(" + dv[i]["Book_ID"].ToString() + ",'" + dv[i]["Book_Name"].ToString() + "','" + dv[i]["Book_Writer"].ToString() + "','";
                sReturn += dv[i]["Book_LastChapter"].ToString() + "','" + dv[i]["Book_LastTime"].ToString() + "'," + dv[i]["Book_TotalVisit"].ToString() + ");\r\n";
            }
        }
        sReturn += "</script>\r\n";
        ds.Dispose();
        dv.Dispose();
        return sReturn;
    }
    /// <summary>
    /// 获得用户当前状态信息
    /// </summary>
    /// <param name="sUserName"></param>
    /// <returns></returns>
    public static string getUserState(string sUserName)
    {
        string sReturn = "<div id='loginstate'>";

        if (sUserName == "")
        {
            sReturn += "<a href='/Login.aspx'>用户登录</a> <a href='/Register.aspx'>新用户注册</a>";
        }
        else
        {
            sReturn += sUserName + ":你好！<a href='/Login.aspx?lb=logout'>注销登录</a> <a href='/ChangePassword.aspx'>更改密码</a>";
        }
        sReturn += "</div>";
        return sReturn;
    }
    /// <summary>
    /// 获得最新更新书籍列表
    /// </summary>
    /// <param name="iBookCount">书籍数目</param>
    /// <returns></returns>
    public static string getBookListNew(string sType,int iBookCount)
    {
        string sHotLimit = ConfigurationSettings.AppSettings["hotlimit"].ToString();
        string sOrderType="";
        if (sType == "all")
            sOrderType = " order by Book_LastTime desc";
        else
            sOrderType = " where Book_WeekVisit> "+sHotLimit+" order by Book_LastTime desc";
        //bookList(80634,'长生界','辰东','第392章 远古遗迹','2009-10-18 19:03:03');
        string sReturn = "";
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.SelectCommand = "select top " + iBookCount.ToString() + " Book_ID,Book_Name,Book_Writer,Book_LastChapter, Book_LastTime from ls_Book";
        ds.SelectCommand +=sOrderType;
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        if (dv != null && dv.Count > 0)
        {
            string bookid;
            string lastchapter;
            string lasttime;
            string bookname;
            string bookwriter;
            for (int i = 0; i < dv.Count; i++)
            {
                bookid = dv[i]["Book_ID"].ToString();
                bookname = dv[i]["Book_Name"].ToString();
                lastchapter = dv[i]["Book_LastChapter"].ToString();
                lasttime = dv[i]["Book_LastTime"].ToString();
                bookwriter=dv[i]["Book_Writer"].ToString();
                sReturn+= "<tr><td><input name=\"checkbox\" type=\"checkbox\" value=" + bookid + " /></td><td><a href=\""+getBookPathByID(bookid)+"\">"+bookname+"</a></td>";
                sReturn+="<td>"+bookwriter+"</td><td><a href=\"/BookDetail.aspx?BookID="+bookid+"\">"+lastchapter+"</a></td><td>"+lasttime+"</td></tr>\r\n";
            }
        }
        sReturn += "</script>\r\n";
        ds.Dispose();
        dv.Dispose();
        return sReturn;
    }
    /// <summary>
    /// 获得书籍信息
    /// </summary>
    /// <param name="sBookID">书籍ID</param>
    /// <returns>书籍信息类</returns>
    public static Book getBookInfo(string sBookID)
    {
        Book book = new Book();

        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.SelectCommand = "select * from ls_Book inner join ls_BookType on Book_Type=BookType_ID where Book_ID=@bookid";
        ds.SelectParameters.Add("bookid", sBookID);
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        if (dv != null && dv.Count > 0)
        {
            book.BookID = dv[0]["Book_ID"].ToString();
            book.BookName = dv[0]["Book_Name"].ToString();
            book.BookWriter = dv[0]["Book_Writer"].ToString();
            book.BookRem = dv[0]["Book_Rem"].ToString();
            book.BookCover = dv[0]["Book_Cover"].ToString();
            book.WeekVisit = dv[0]["Book_WeekVisit"].ToString();
            book.TotalVisit = dv[0]["Book_TotalVisit"].ToString();
            book.BookType = dv[0]["BookType_Name"].ToString();
            book.AddTime = dv[0]["Book_AddTime"].ToString();
            book.UserName = dv[0]["Book_UserName"].ToString();
            book.BookTypeID = dv[0]["Book_Type"].ToString();
            book.TotalRMD = dv[0]["Book_TotalTicket"].ToString();
            if (dv[0]["Book_Active"].ToString() == "False")
                book.BookState = "已完成";
            else
                book.BookState = "连载中";
            book.BookList = getList(sBookID);
        }
        ds.Dispose();
        dv.Dispose();
        return book;
    }
    /// <summary>
    /// 获得某书籍的目录列表
    /// </summary>
    /// <param name="sBookID">书籍编号</param>
    /// <returns>目录列表</returns>
    public static string getList(string sBookID)
    {
        //slist('文学家','长生界','http://read.wenxuejia.net/files/article/html/2/2175/index.html','Kiee','97%');
        string sReturn = "<script language=\"javascript\" type=\"text/javascript\">\r\n";
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.SelectCommand = "select * from ls_List where List_BookID=@bookid order by List_FailCount+List_RegFailCount";
        ds.SelectParameters.Add("bookid", sBookID);
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        if (dv != null && dv.Count > 0)
        {
            for (int i = 0; i < dv.Count; i++)
            {
                string sHealth=(Convert.ToString(10000/(100+(int)dv[i]["List_RegFailCount"]+(int)dv[i]["List_FailCount"])))+"%";
                sReturn += "sList('" + dv[i]["List_SiteName"].ToString() + "','" + dv[i]["List_BookName"].ToString() + "','" + dv[i]["List_URL"].ToString() + "','" + dv[i]["List_UserName"].ToString() + "','"+sHealth+"');\r\n";
            }
        }
        sReturn += "</script>\r\n";
        ds.Dispose();
        dv.Dispose();
        return sReturn;
    }
    /// <summary>
    /// 根据检索结果获得书籍列表
    /// </summary>
    /// <param name="Request">页面请求</param>
    /// <returns>返回脚本</returns>
    public static string getBookSearch(HttpRequest Request)
    {
        
        //searchList(11,'星辰变','我吃西红柿','连载中','武侠修真','大结局',2147414);
        string sReturn="";

        if (Request.QueryString["SearchKey"] != null && Request.QueryString["SearchType"] != null)
        {
            string sBookName = Request.QueryString["SearchKey"].ToString();
            string sSearchType = Request.QueryString["SearchType"].ToString();
            string bookname;
            string writer;
            string sBookState;
            //默认采用模糊检索
            string sSQL = " where Book_Name like '%'+@bookname+'%' and Book_Writer like '%'+@writer+'%' ";
            if (sSearchType == "ForAuthorName")
            {
                bookname = "%";
                writer = sBookName;
                //根据作者检索而且是精确查找
                if (Request.QueryString["Really"] != null)
                    sSQL = " where Book_Name like '%'+@bookname+'%' and Book_Writer=@writer";
                //根据作者检索而且是模糊查找
                else
                    sSQL = " where Book_Name like '%'+@bookname+'%' and Book_Writer like '%'+@writer+'%' ";
            }
            //根据书名检索
            else
            {
                bookname = sBookName;
                writer = "%";
                //根据书名检索而且是精确查找
                if (Request.QueryString["Really"] != null)
                    sSQL = " where Book_Name =@bookname and Book_Writer like '%'+@writer+'%' ";
                //根据书名检索而且是模糊查找
                else
                    sSQL = " where Book_Name like '%'+@bookname+'%' and Book_Writer like '%'+@writer+'%' ";
            }
            SqlDataSource ds = new SqlDataSource();
            ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
            //模糊查找

            ds.SelectCommand = "select Book_ID,Book_Name,Book_Writer,Book_Active,BookType_Name,Book_LastChapter,Book_TotalVisit from ls_Book inner join ls_BookType on Book_Type=BookType_ID " + sSQL + " order by Book_TotalVisit desc";
            ds.SelectParameters.Add("bookname", bookname);
            ds.SelectParameters.Add("writer", writer);
            DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
            if (dv != null && dv.Count > 0)
            {
                sReturn = "<script language=\"javascript\" type=\"text/javascript\">\r\n";
                for (int i = 0; i < dv.Count; i++)
                {
                    if (dv[i]["Book_Active"].ToString() == "False")
                        sBookState = "已完成";
                    else
                        sBookState = "连载中";
                    sReturn += "searchList(" + dv[i]["Book_ID"].ToString() + ",'" + dv[i]["Book_Name"].ToString() + "','";
                    sReturn += dv[i]["Book_Writer"].ToString() + "','" + sBookState + "','" + dv[i]["BookType_Name"].ToString() + "','" + dv[i]["Book_LastChapter"].ToString() + "'," + dv[i]["Book_TotalVisit"].ToString() + ");\r\n";
                }
                sReturn += "</script>\r\n";
            }
            else
            {
                if (Request.QueryString["Really"] != null)
                {
                    sReturn = "<tr><td colspan='7'><a href='/BookInfo.aspx'>没有找到书籍，您可将“精确查找”前勾打掉后再搜，或者在此添加书籍并检索书目</a></td></tr>";
                }
                else
                {
                    sReturn = "<tr><td colspan='7'><a href='/BookInfo.aspx'>没有找到书籍，您可以在此添加本书，并检索书目。</a></td></tr>";
                }
            }
            ds.Dispose();
            dv.Dispose();
        }
        else
        {
            sReturn = "<tr><td colspan='7'>请设置检索条件</td></tr>";
        }
        return sReturn;
        
    }
    /// <summary>
    /// 获得当前的检索状态字符串
    /// </summary>
    /// <param name="Request">请求</param>
    /// <returns></returns>
    public static string getSearchState(HttpRequest  Request)
    {
        string sReally="";
        string sBookName="";
        string sSearchType="";
        bool bsearch=true;
        string sReturn="";
        if (Request.QueryString["Really"] != null)
            sReally = "精确查找";
        else
            sReally = "模糊查找";

        if (Request.QueryString["SearchType"] != null)
        {

            if (Request.QueryString["SearchType"].ToString() == "ForAuthorName")
            {
                sSearchType = "作者";
            }
            else
            {
                sSearchType = "书名";
            }
        }
        else
        {
            bsearch = false;
        }
        if (Request.QueryString["SearchKey"] != null)
        {
            sBookName = Request.QueryString["SearchKey"].ToString();
        }
        else
        {
            bsearch = false;
        }

        if (bsearch == true)
        {
            sReturn = "关键字：" + sBookName + "，根据" + sSearchType + "以“" + sReally+"”方式检索。";
        }

        return sReturn;
    }
    /// <summary>
    /// 获得书籍的书站名称下拉菜单
    /// </summary>
    /// <param name="sBookID">书籍ID</param>
    /// <returns>一个select 下来菜单</returns>
    public static string getSiteSelect(string sBookID)
    {
        string sReturn = "<select id='select'>\r\n";
        sReturn+="<option value='0' selected='selected'>更新网站</option>\r\n";
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.SelectCommand = "select distinct Site_ID,Site_Name from ls_List inner join ls_Site on Site_ID=List_SiteID where List_BookID=@bookid order by Site_ID";
        ds.SelectParameters.Add("bookid", sBookID);
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        if (dv != null && dv.Count > 0)
        {
            for (int i = 0; i < dv.Count; i++)
            {
                sReturn += "<option value='"+dv[i]["Site_ID"].ToString()+"'>"+dv[i]["Site_Name"].ToString()+"</option>\r\n";
            }
        }
        sReturn += "</select>\r\n";
        ds.Dispose();
        dv.Dispose();
        return sReturn;
    }

    /// <summary>
    /// 获得某本书籍最新章节的列表
    /// </summary>
    /// <param name="sBookID"></param>
    /// <param name="iRows"></param>
    /// <returns></returns>
    public static string getChapterList(HttpRequest Request, int iRows)
    {
        //chapterList('http://www.e193.net/html/10892/521.html','卡徒 第五百二十节 狼来了！',14,24,'小说天下','2009-10-20 18:43:13');
        string sReturn = "<script language=\"javascript\" type=\"text/javascript\">\r\n";

        string sBookID = Request.QueryString["BookID"].ToString();
        string sSiteID = "%";
        if (Request.QueryString["SiteID"] != null)
            sSiteID = Request.QueryString["SiteID"].ToString();

        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.SelectCommand = "select Top "+iRows.ToString()+" Book_Name,Chapter_Title,Chapter_URL,Chapter_AddTime,Site_ID,Site_Name,Book_ID from ls_Chapter inner join ls_Book on Book_ID=Chapter_BookID  ";
        ds.SelectCommand += " inner join ls_Site on Site_ID=Chapter_SiteID where Chapter_BookID=@bookid and Chapter_SiteID like @siteid order by Chapter_AddTime desc";
        ds.SelectParameters.Add("bookid", sBookID);
        ds.SelectParameters.Add("siteid", sSiteID);
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        if (dv != null && dv.Count > 0)
        {
            for (int i = 0; i < dv.Count; i++)
            {
                sReturn += "chapterList('" + dv[i]["Chapter_URL"].ToString() + "','" + dv[i]["Book_Name"].ToString() + " " + dv[i]["Chapter_Title"].ToString() + "'," + dv[i]["Site_ID"].ToString();
                sReturn += ","+dv[i]["Book_ID"].ToString()+",'"+dv[i]["Site_Name"].ToString()+"','"+dv[i]["Chapter_AddTime"].ToString()+"');\r\n";
            }
        }
        sReturn += "</script>\r\n";
        dv.Dispose();
        ds.Dispose();
        return sReturn;
    }
    /// <summary>
    /// 更新登录信息
    /// </summary>
    /// <param name="sUserName">用户名</param>
    public static int updateLogin(string sUserName)
    {
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.UpdateCommand = "update ls_User set User_LoginCount=User_LoginCount+1,User_LastLogin=getdate() where User_Name=@username";
        ds.UpdateParameters.Add("username", sUserName);
        int iRowEffect=ds.Update();
        return iRowEffect;
    }
    /// <summary>
    /// 获得站点信息
    /// </summary>
    /// <param name="sSiteID">站点ID</param>
    /// <returns>站点信息类</returns>
    public static SiteInfo getSiteInfo(string sSiteID)
    {
        SiteInfo siteinfo = new SiteInfo();
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.SelectCommand = "select * from ls_Site where Site_ID=@siteid";
        ds.SelectParameters.Add("siteid", sSiteID);
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        if (dv != null && dv.Count > 0)
        {
            siteinfo.SiteID = dv[0]["Site_ID"].ToString();
            siteinfo.SiteName = dv[0]["Site_Name"].ToString();
            siteinfo.SiteEncode = dv[0]["Site_Encode"].ToString();
            siteinfo.SiteMethod = dv[0]["Site_Method"].ToString();
            siteinfo.SearchURL = dv[0]["Site_SearchURL"].ToString();
            siteinfo.SearchParam = dv[0]["Site_SearchParam"].ToString();
            siteinfo.ResultReg = dv[0]["Site_ResultReg"].ToString();
            siteinfo.ResultOrder = dv[0]["Site_ResultOrder"].ToString();
            siteinfo.ListFormat = dv[0]["Site_ListFormat"].ToString();
            siteinfo.SiteRedirect = dv[0]["Site_Redirect"].ToString();
            siteinfo.ResultReg2 = dv[0]["Site_ResultReg2"].ToString();
            siteinfo.ResultOrder2 = dv[0]["Site_ResultOrder2"].ToString();
            siteinfo.ListFormat2 = dv[0]["Site_ListFormat2"].ToString();
        }
        return siteinfo;
    }
    /// <summary>
    /// 在指定网站检索与书名一样的书籍目录
    /// </summary>
    /// <param name="siteinfo">站点信息</param>
    /// <param name="sKeyWord">检索关键字</param>
    /// <param name="bExactly">是否精确查找</param>
    /// <returns>格式化字符串</returns>
    public static string getListSearch(SiteInfo siteinfo, string sKeyWord,bool bExactly)
    {
        string sBookName;
        string sWriter;
        string sListURL;
        string[] sResultOrder = siteinfo.ResultOrder.Split(',');
       
        string sResult="";
        //将书籍名称以站点的编码方式编码。
        //这样就不会乱码了。
        string sKeyWordEncode = HttpUtility.UrlEncode(sKeyWord, Encoding.GetEncoding(siteinfo.SiteEncode));
        //替换参数。
        string sParam=siteinfo.SearchParam;
        sParam = sParam.Replace("<#KEYWORD>", sKeyWordEncode);
        //获取数据
        string sHtml=GetData.getHtml(siteinfo.SearchURL, sParam, siteinfo.SiteEncode, siteinfo.SiteMethod);
        //分析数据

        Match match = Regex.Match(sHtml, siteinfo.ResultReg, RegexOptions.IgnoreCase | RegexOptions.Multiline);
        while (match.Success)
        {
            sBookName=match.Groups[Convert.ToInt32(sResultOrder[0])].Value;
            sWriter = match.Groups[Convert.ToInt32(sResultOrder[1])].Value;
            sListURL = match.Groups[Convert.ToInt32(sResultOrder[2])].Value;


            //去掉前后空格
            sBookName = GetData.clearHTML(sBookName,"").Trim();
            sWriter = GetData.clearHTML(sWriter, "");
            sListURL = GetData.clearHTML(sListURL, "");
            sListURL = siteinfo.ListFormat.Replace("<#LIST>", sListURL);

            match = match.NextMatch();
            //<tr><td><input name='checkbox' type='checkbox' value='12' /></td><td></td>二牛中文<td>星辰变</td><td>我吃西红柿</td><td><a href='http://www.lieshu.net/htm/1/index.htm'>http://www.lieshu.net/htm/1/index.htm</a></td></tr>
            //如果限定了精确查找，那么只有完全等同的时候才添加。
            if (sBookName != sKeyWord && bExactly == true || BookManger.checkList(sListURL))
                continue;
            else
                sResult += "<tr><td><input name='checkbox' type='checkbox' value='" + siteinfo.SiteID + "|" + sListURL + "' /></td><td>" + siteinfo.SiteName + "</td><td>" + sBookName + "</td><td>" + sWriter + "</td><td><a href='/PageClear.aspx?pagename=" + sListURL + "'>" + sListURL + "</a></td></tr>";         
        }
        //如果没有用第一种正则表达式没有检索到结果，并且网站在单一结果时自动转向的，则调用第二个再次检索。
        if (sResult == "" && siteinfo.SiteRedirect == "1")
        {
            match = Regex.Match(sHtml, siteinfo.ResultReg2, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            while (match.Success)
            {
                string[] sResultOrder2 = siteinfo.ResultOrder2.Split(',');
                sBookName = match.Groups[Convert.ToInt32(sResultOrder2[0])].Value;
                sWriter = match.Groups[Convert.ToInt32(sResultOrder2[1])].Value;
                sListURL = match.Groups[Convert.ToInt32(sResultOrder2[2])].Value;


                //去掉前后空格
                sBookName = GetData.clearHTML(sBookName, "");
                sWriter = GetData.clearHTML(sWriter, "");
                sListURL = GetData.clearHTML(sListURL, "");
                sListURL = siteinfo.ListFormat2.Replace("<#LIST>", sListURL);

                match = match.NextMatch();
                //<tr><td><input name='checkbox' type='checkbox' value='12' /></td><td></td>二牛中文<td>星辰变</td><td>我吃西红柿</td><td><a href='http://www.lieshu.net/htm/1/index.htm'>http://www.lieshu.net/htm/1/index.htm</a></td></tr>
                //如果限定了精确查找，那么只有完全等同的时候才添加。
                if (sBookName != sKeyWord && bExactly == true||BookManger.checkList(sListURL))
                    continue;
                else
                    sResult += "<tr><td><input name='checkbox' type='checkbox' value='" +siteinfo.SiteID +"|"+sListURL+ "' /></td><td>" + siteinfo.SiteName + "</td><td>" + sBookName + "</td><td>" + sWriter + "</td><td><a href='/PageClear.aspx?pagename=" + sListURL + "'>" + sListURL + "</a></td></tr>";
            }
        }
        return sResult;
    }
    /// <summary>
    /// 建立书籍介绍页
    /// </summary>
    /// <param name="sBookID">书籍ID</param>
    /// <param name="iInterval">时间间隔</param>
    /// <returns>放回书籍页地址</returns>
    public static string buildBookPage(string sBookID,int iInterval)
    {
            const string sTemplate = "/model/BookInfoTemplate.htm";
            //模板映射
            string sTemplateMap = HttpContext.Current.Server.MapPath(sTemplate);
            //
            if(iInterval==0)
                iInterval = Convert.ToInt32(ConfigurationSettings.AppSettings["pagemin"].ToString());

            string sDir = "/book/"+(Convert.ToInt32(sBookID)/1000).ToString()+"/";
            string sDirMap = HttpContext.Current.Server.MapPath(sDir);
            string sPage = sDir+sBookID+".htm";
            string sPageMap = HttpContext.Current.Server.MapPath(sPage);

            //增加受访问数
            BookManger.visitBook(sBookID);

            //页面存在标记
            bool bPageExists = false;
            if (File.Exists(sPageMap))
            {
                FileInfo fileinfo = new FileInfo(sPageMap);
                if (DateTime.Now.Subtract(fileinfo.LastWriteTime).Hours <iInterval)
                    bPageExists = true;
            }

            if (!bPageExists)
            {
                if (!Directory.Exists(sDirMap))
                    Directory.CreateDirectory(sDirMap);
                StreamReader sr = new StreamReader(sTemplateMap);
                string sModel = sr.ReadToEnd();
                sr.Close();
                //替换

                Book book = WebMake.getBookInfo(sBookID);
                
                sModel = sModel.Replace("<#BOOKID>", book.BookID);
                sModel = sModel.Replace("<#BOOKNAME>",book.BookName);
                sModel = sModel.Replace("<#BOOKWRITER>", book.BookWriter);
                sModel = sModel.Replace("<#WEEKVISIT>", book.WeekVisit);
                sModel = sModel.Replace("<#TOTALVISIT>", book.TotalVisit);
                sModel = sModel.Replace("<#TOTALRMD>", book.TotalRMD);
                sModel = sModel.Replace("<#BOOKREM>", book.BookRem);
                sModel = sModel.Replace("<#BOOKSTATE>", book.BookState);
                sModel = sModel.Replace("<#SLIST>", book.BookList);
                sModel = sModel.Replace("<#BOOKCOVER>", book.BookCover);
                sModel = sModel.Replace("<#BOOKTYPE>", book.BookType);
                sModel = sModel.Replace("<#USERNAME>", book.UserName);
                sModel = sModel.Replace("<#ADDTIME>", book.AddTime);
                sModel = sModel.Replace("<#TYPESELECT>",WebMake.getTypeSelect(book.BookTypeID));

                //保存
                StreamWriter sw = new StreamWriter(sPageMap, false, Encoding.UTF8);
                sw.WriteLine(sModel);
                sw.Close();
            }
            return sPage;
    }

    /// <summary>
    /// 获得书籍类型的下拉菜单
    /// </summary>
    /// <param name="booktype">书籍类型ID</param>
    /// <returns></returns>
    public static string getTypeSelect(string  booktype)
    {
        string sReturn = "<select id='select_booktype'>\r\n";
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.SelectCommand = "select distinct BookType_ID,BookType_Name from ls_BookType  order by BookType_ID";
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        if (dv != null && dv.Count > 0)
        {
            for (int i = 0; i < dv.Count; i++)
            {
                if (booktype == dv[i]["BookType_ID"].ToString())
                    sReturn += "<option value='" + dv[i]["BookType_ID"].ToString() + "' selected='selected'>" + dv[i]["BookType_Name"].ToString() + "</option>\r\n";
                else
                    sReturn += "<option value='" + dv[i]["BookType_ID"].ToString() + "'>" + dv[i]["BookType_Name"].ToString() + "</option>\r\n";
            }
        }
        sReturn += "</select>\r\n";
        ds.Dispose();
        dv.Dispose();
        return sReturn;
    }
    /// <summary>
    /// 获得排行榜的
    /// </summary>
    /// <param name="dv">数据集</param>
    /// <param name="iStart">开始</param>
    /// <param name="iCount">总数</param>
    /// <param name="sType">类型</param>
    /// <returns></returns>
    public static string getTopList(DataView dv, int iStart, int iCount)
    {
        string temp="";
        for (int i = iStart; i < iStart+iCount&&i<dv.Count; i++)
            temp += "<tr><td>" + (i + 1) + "</td><td>" + dv[i]["BookType_Name"].ToString() + "</td><td><a href='" + getBookPathByID(dv[i]["Book_ID"].ToString()) + "'>" + dv[i]["Book_Name"].ToString() + "</a></td></tr>\r\n";

        return temp;
    }

    public static string getSiteRegList()
    {
        SqlDataSource ds = new SqlDataSource();
        string sReturnStr = "";
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.SelectCommand = "select * from ls_Site ";
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        for (int i = 0; i < dv.Count; i++)
        {
            sReturnStr += "\n" + dv[i]["Site_Name"].ToString();
            sReturnStr += "\v" + dv[i]["Site_Index"].ToString();
            sReturnStr += "\v" + dv[i]["Site_NameReg"].ToString();
            sReturnStr += "\v" + dv[i]["Site_ListReg"].ToString();
            sReturnStr += "\v" + dv[i]["Site_TitleReg"].ToString();
            sReturnStr += "\v" + dv[i]["Site_ContentReg"].ToString();
            sReturnStr += "\v" + dv[i]["Site_ExceptReg"].ToString();
            sReturnStr += "\v" + dv[i]["Site_DefaultIndex"].ToString();
        }
        sReturnStr=sReturnStr.Substring(1,sReturnStr.Length-1);
        return sReturnStr;
    }
    public static string getBookPathByID(string sBookID)
    {
        return  "/book/" + (Convert.ToInt32(sBookID) / 1000).ToString() + "/"+sBookID + ".htm";;
    }
    /// <summary>
    /// 建立最新更新页
    /// </summary>
    /// <param name="lb">类别hot 或者all</param>
    /// <returns></returns>
    public static void buildLastUpdatePage(string lb)
    {
        string sType = "";
        string sFile = "";
        if (lb == "hot")
        {
            sType = "热门小说";
            sFile = "/LastUpdateHot.htm";
        }
        else
        {
            sType = "全部小说";
            sFile = "/LastUpdateAll.htm";
        }

        const string sTemplate = "/model/LastUpdateTemplate.htm";
        string sTemplateMap = HttpContext.Current.Server.MapPath(sTemplate);

        string sFileMap = HttpContext.Current.Server.MapPath(sFile);
        //页面存在标记
        bool bPageExists = false;
        if (File.Exists(sFileMap))
        {
            FileInfo fileinfo = new FileInfo(sFileMap);
            if (DateTime.Now.Subtract(fileinfo.LastWriteTime).Minutes < -1) //最小的间隔为2分钟
                bPageExists = true;
        }

        if (!bPageExists)
        {
            StreamReader sr = new StreamReader(sTemplateMap);
            string sModel = sr.ReadToEnd();
            sr.Close();
            //替换
            sModel = sModel.Replace("<#LB>", lb);
            sModel = sModel.Replace("<#TYPE>", sType);
            sModel = sModel.Replace("<#NEWLIST>", WebMake.getBookListNew(lb, 20));
            //保存
            StreamWriter sw = new StreamWriter(sFileMap, false, Encoding.UTF8);
            sw.WriteLine(sModel);
            sw.Close();
        }
    }
    /// <summary>
    /// 建立主页
    /// </summary>
    public static void buildIndexPage()
    {
        int ipagemin = Convert.ToInt32(ConfigurationSettings.AppSettings["pagemin"].ToString());
        ipagemin = -1;
        // 首页模板
        const string sIndexTemplate = "/model/indextemplate.htm";
        string sIndexTemplateMap= HttpContext.Current.Server.MapPath(sIndexTemplate);
        //
        const string sIndex = "/index.htm";
        string sIndexMap = HttpContext.Current.Server.MapPath(sIndex);

        //页面存在标记
        bool bPageExists = false;
        if (File.Exists(sIndexMap))
        {
            FileInfo fileinfo = new FileInfo(sIndexMap);
            if (DateTime.Now.Subtract(fileinfo.LastWriteTime).Hours< ipagemin)
                bPageExists = true;
        }

        if (!bPageExists)
        {
            StreamReader sr = new StreamReader(sIndexTemplateMap);
            string sModel = sr.ReadToEnd();
            sr.Close();
            //替换

            sModel = sModel.Replace("<#BOOKHOT>", WebMake.getHotBook(65));
            //保存
            StreamWriter sw = new StreamWriter(sIndexMap, false, Encoding.UTF8);
            sw.WriteLine(sModel);
            sw.Close();
        }
    }
    public static void buildTopViewPage(string lb)
    {

        int ipagemin = Convert.ToInt32(ConfigurationSettings.AppSettings["pagemin"].ToString());
        ipagemin = -1;
        string sPage = "";
        string sPageMap = "";
        //标题
        string sTitle = "";
        string sSQL = "";
        //模板物理地址

        //4个列表
        string sBookList1 = "";
        string sBookList2 = "";
        string sBookList3 = "";
        switch (lb)
        {
            case "week":
                sPage = "/TopWeekView.htm";
                sTitle = "周 排 行";
                sSQL = " order by Book_WeekVisit desc ";
                break;
            case "total":
                sPage = "/TopTotalView.htm";
                sTitle = "总 排 行";
                sSQL = " order by Book_TotalVisit desc ";
                break;
            default:
                sPage = "/TopTotalTicket.htm";
                sTitle = "推 荐 榜";
                sSQL = " order by Book_TotalTicket desc ";
                break;
        }
        sPageMap = HttpContext.Current.Server.MapPath(sPage);

        bool bPageExists = false;
        if (File.Exists(sPageMap))
        {
            FileInfo fileinfo = new FileInfo(sPageMap);
            if (DateTime.Now.Subtract(fileinfo.LastWriteTime).Hours < ipagemin)
                bPageExists = true;
        }
        //如果不存在，就建立文件。
        if (!bPageExists)
        {
            //获得3列数据
            // 格式 list(92005,'重生之都市狂龙',25,192024);
            SqlDataSource ds = new SqlDataSource();
            ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
            ds.SelectCommand = "select top 60 Book_ID,Book_Name,Book_WeekVisit,Book_TotalVisit,Book_TotalTicket,BookType_Name  from ls_Book inner join ls_BookType on BookType_ID=Book_Type" + sSQL;
            DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
            if (dv != null && dv.Count > 0)
            {
                sBookList1 = WebMake.getTopList(dv, 0, 20);
                sBookList2 = WebMake.getTopList(dv, 20, 20);
                sBookList3 = WebMake.getTopList(dv, 40, 20);
            }
            ds.Dispose();
            dv.Dispose();

            //读取模板。
            string sTemplateMap = HttpContext.Current.Server.MapPath("/model/TopViewTemplate.htm");
            StreamReader sr = new StreamReader(sTemplateMap);
            string sModel = sr.ReadToEnd();
            sr.Close();

            sModel = sModel.Replace("<#TITLE>", sTitle);
            sModel = sModel.Replace("<#BOOK1>", sBookList1);
            sModel = sModel.Replace("<#BOOK2>", sBookList2);
            sModel = sModel.Replace("<#BOOK3>", sBookList3);
            sModel = sModel.Replace("<#LB>", lb);
            StreamWriter sw = new StreamWriter(sPageMap, false, Encoding.UTF8);
            sw.WriteLine(sModel);
            sw.Close();
        }

    }

}
